package scala

import scala.io.Source

object Demo25Score {
  def main(args: Array[String]): Unit = {
    /**
      * 2、统计学生的总分
      *
      */


    //读取分数表
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList


    //取出学号和分数
    val idAndScore: List[(String, Double)] = scores.map(score => {
      val split: Array[String] = score.split(",")
      (split(0), split(2).toDouble)
    })


    //按照学号分组
    val group: Map[String, List[(String, Double)]] = idAndScore.groupBy(kv => kv._1)


    //统计学生的总分

    val sumScores: Map[String, Double] = group.map(kv => {
      val id: String = kv._1
      //取出一个人所有的分数
      val ss: List[Double] = kv._2.map(kv1 => kv1._2)

      //计算总分
      val sumScore: Double = ss.sum

      (id, sumScore)
    })


    sumScores.foreach(println)

    println("=" * 100)


    /**
      * 1、统计总分年级排名前十学生各科的分数
      *
      */


    //将map 转换成list  map 不能排序
    val sumScoreList: List[(String, Double)] = sumScores.toList


    //按照分数降序排序，取前十
    val sortByScore: List[(String, Double)] = sumScoreList.sortBy(kv => -kv._2)


    //取前十
    val top10: List[(String, Double)] = sortByScore.take(10)

    //取出id
    val ids: List[String] = top10.map(kv => kv._1)


    //从分数表中取出前十的学生
    val top10Score: List[String] = scores.filter(score => {
      val split: Array[String] = score.split(",")
      val id: String = split(0)

      //判断id 是否在ids  中存在
      ids.contains(id)
    })

    top10Score.foreach(println)


    println("=" * 100)

    /**
      *
      * 2、统计总分大于年级平均分的学生
      *
      */

    //计算年级平均分
    val ssScore: Double = sumScores.values.sum

    //年级平均分
    val avgScore: Double = ssScore / sumScores.size

    println(avgScore)

    //过滤总分打印年级平均分的学生
    val sumScoGtAvgSco: Map[String, Double] = sumScores.filter(kv => {
      val sumSco: Double = kv._2
      sumSco > avgScore
    })

    sumScoGtAvgSco.foreach(println)


  }
}
